let layer = layui.layer //弹层
    ,table = layui.table //表格
    form = layui.form,$ = layui.jquery,changeList=[],laydate = layui.laydate,indexs = 0,checkboxs =false;

lay('.starttime').each(function(){
    laydate.render({
        elem: this
    });
});
let colourList = getdictionary(6, 41);//颜色
let unitList = getdictionary(6, 42);//单位
let productInfo = [];
table.render({
    elem: '#purchaseorder'
    ,data:[]
    , id: 'purchaseordertableid'
    , cellMinWidth: 120
    ,cols: [[
        {checkbox: true, title:'选择'}
        ,{field:'exportNo', title:'合同编号',width: 200,style:"overflow:hidden"}
        ,{field:'customerContractNo', title:'客户合同号',width: 200,style:"overflow:hidden"}
        ,{field:'customerName', title:'客户名称',hide:true}
        ,{field:'customerLevelCode', title:'客户等级编码',hide:true}
        ,{field:'customerLevelName', title:'客户等级名称'}
        ,{field:'signingName', title:'签约公司',style:"overflow:hidden"}
        ,{field:'deliverDate', title:'签约日期',sort:true, templet: function(d) {return layui.util.toDateString(d.deliverDate,"yyyy-MM-dd");}}
        ,{field:'bankName', title:'银行'}
        ,{field:'leadTime', title:'备货期限'}
        ,{field:'shipmentDate', title:'出运日期',sort:true, templet: function(d) {return layui.util.toDateString(d.deliverDate,"yyyy-MM-dd");}}
        ,{field:'transportModel', title:'运输方式'}
        ,{field:'salesmanName', title:'业务员'}
    ]]
    ,height: 400
    ,page: true
    , parseData: function(res){
        return {
            "code": res.status,
            "count": res.total,
            "data": res.data
        };
    }
    ,done: function (res, curr, count) {
        let exIdArr = [];
        if(res.data!=null && res.data.length>0){
            exIdArr.push(res.data[0].exportId)
        }
        table.render({
            elem: '#product'
            , url: "purchase/selectExportProductByExIds"
            , method:'post'
            , contentType: 'application/json;charset=utf-8'
            ,cols: [[
                {checkbox: true, title: '选择'}
                , {field: 'productNo', title: '产品编码',width: 120}
                , {field: 'specNo', title: '规格编码',width: 120}
                , {field: 'chineseName', title: '中文名称',width: 120}
                , {field: 'englishName', title: '英文名称',width: 120}
                , {field: 'unit', title: '单位',
                    templet: function(data) {
                        let name = "";
                        $.each(unitList, function(index, item) {
                            if (data.unit==item.code){
                                name = item.name;
                                return ;
                            }
                        });
                        return name;
                    }
                }
                , {field: 'colour', title: '颜色',
                    templet: function(data) {
                        let name = "";
                        $.each(colourList, function(index, item) {
                            if (data.colour==item.code){
                                name = item.name;
                                return ;
                            }
                        });
                        return name;
                    }
                }
                , {field: 'surplusNum', title: '数量',width: 100,templet: function(d) { return d.surplusNum?d.surplusNum:0}}
                , {field: 'amount', title: '剩余数量',width: 100,templet: function(d) { return d.amount?d.amount:0}}
                , {field: 'price', title: '单价',width: 100 ,hide:true,
                    templet: function(d) {
                        return d.price?Number(d.price).toFixed(4):0.00;
                    }
                }
                , {field: 'costPrice', title: '成本单价',width: 100,
                    templet: function(d) {
                        return d.costPrice?Number(d.costPrice).toFixed(4):0.00;
                    }
                }
                , {field: 'taxedCostPrice', title: '含税单价',width: 100, hide:true,
                    templet: function(d) {
                        return d.taxedCostPrice?Number(d.taxedCostPrice).toFixed(4):0.00;
                    }
                }
                , {field: 'untaxedCostPrice', title: '未税单价',width: 100, hide:true,
                    templet: function(d) {
                        return d.untaxedCostPrice?Number(d.untaxedCostPrice).toFixed(4):0.00;
                    }
                }
                , {field: 'grossWeight', title: '毛重',width: 100,
                    templet: function(d) {
                        return d.grossWeight?d.grossWeight.toFixed(2):0.00;
                    }
                }
                , {field: 'volume', title: '体积',width: 100,
                    templet: function(d) {
                        return d.volume?d.volume.toFixed(2):0.00;
                    }
                }
                , {field: 'netWeight', title: '净重',width: 100,
                    templet: function(d) {
                        return d.netWeight?d.netWeight.toFixed(2):0.00;
                    }
                }
                , {field: 'outPackLength', title: '外包装长',width: 100}
                , {field: 'outPackWidth', title: '外包装宽',width: 100}
                , {field: 'outPackHeight', title: '外包装高',width: 100}
                , {field: 'outPackSize', title: '外包装尺寸',width: 100}
                , {field: 'outPackNum', title: '外包装数量',width: 100}
                , {field: 'requestDeliveryDate', title: '要求交货日期',width: 100,
                    templet: function(d) {
                        if(d.requestDeliveryDate){
                            return layui.util.toDateString(d.requestDeliveryDate,"yyyy-MM-dd");
                        }
                        return "";
                    }
                }
                , {field: 'salesContractNo', title: '销售合同号',width: 150}

            ]]
            ,id: 'producttableid'
            , where: {
                exIds : exIdArr,
                /*pageNum :0,
                pageSize:10*/
            }
            ,height: 400
            ,done:function () {
                $("th .layui-table-cell.laytable-cell-checkbox").html("选择");
            }
        });
    }
});

//监听复选框主表
table.on('checkbox(purchaseordertable)', function (data) {
    if(data.type == 'all'){
        //allDataOperation(data);
    }else if(data.type == 'one'){
        //外销合同号
        let exportNo = data.data["exportNo"];
        let sum = getReceivePaymentByContractNo(exportNo);
        //账期
        let period = data.data["customerAccountingPeriod"];
        //是否补货(0:否 1:是)
        let whetherToReplenish = data.data["whetherToReplenish"];
        if (isEmpty(period) && whetherToReplenish === 0 && sum === 0) {
            if (data.checked === true) {
                layer.msg("该合同未收预收款，请稍后再做采购，如有疑问请联系该单据业务员", {icon: 5});
                data.checked = false;
            }
        } else {
            oneDataOperation(data);
        }

    }

});

//通过外销合同号获取收款明细信息
function getReceivePaymentByContractNo(exportNo) {
    let sum = 0;
    $.ajax({
        url: "receivePayment/getReceivePaymentByContractNo",
        async: false,
        data: {
            contractNo : exportNo
        },
        success: function (data) {
            if (data.status == 200) {
                sum = data.data.length;
            }
        }
    })

    return sum;
}


function allDataOperation(data) {
    //第一个表格选中的数据
    let parentTableCheckedData =   table.checkStatus("purchaseordertableid").data;
    if(parentTableCheckedData.length > 0){
        let ids = [];
        for(let i in parentTableCheckedData){
            ids.push(parentTableCheckedData[i].id);
        }
        let datas = JSON.stringify(ids);
        $.ajax({
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:datas,
            url:"purchase/selectExportProductByExIds",
            success:function(res){
                if(res.status == 200){
                    let stockData = res.data;
                    //获取被选中的子表数据
                    addCheckedToChangeList(stockData, data.checked);
                    return false;
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
            }
        });
    }
}

//获取被选中的子表数据
function addCheckedToChangeList(checkedChildData, checkFlag) {
    if(checkedChildData.length > 0){
        let temp = [];
        for (let i in changeList) {
            for (let j in checkedChildData) {
                let flag = checkedChildData[j].id == changeList[i].exportId;
                if (!flag && checkFlag) {
                    let child = $("#product").next().find('tbody input[type="checkbox"]');
                    child.each(function(index, item){
                        item.checked = checkFlag;
                    });
                    temp.push(checkedChildData[j]);
                }
                if(flag && !checkFlag){
                    changeList.splice(i,1);
                }
            }
        }
        if(temp.length > 0){
            changeList.push.apply(changeList, temp);
        }
    }
}

function oneDataOperation(data) {
    let exportIds = [];
    exportIds.push(data.data.exportId);
    table.reload('producttableid', {
        page: {
            limit: 10,
            curr: 1
        }
        ,where: {
            exIds:exportIds
        },
        done: function (res, curr, count) {
            let child = $("#product").next().find('tbody input[type="checkbox"]');
            child.each(function(index, item){
                item.checked = data.checked;
            });
            if(res.data!=null){
                if(data.checked){
                    for(let i = 0; i < res.data.length; i++){
                        res.data[i].companyId=data.data.companyId;
                        res.data[i].salesmanCode=data.data.salesmanCode;
                        res.data[i].signingCode=data.data.signingCode;
                        res.data[i].signingName=data.data.signingName;
                        res.data[i].bankCode=data.data.bankCode;
                        res.data[i].bankName=data.data.bankName;
                        res.data[i].customerLevelCode=data.data.customerLevelCode;
                        res.data[i].customerLevelName=data.data.customerLevelName;
                        res.data[i].importRemark=data.data.importRemark;
                        res.data[i].whetherToReplenish=data.data.whetherToReplenish;
                        res.data[i].customerComplaintNo=data.data.customerComplaintNo;
                        changeList.push(res.data[i]);
                    }
                }else{
                    if(changeList.length > 0){
                        for(let i = 0; i < res.data.length; i++){
                            deleteData(res.data[i]);
                        }
                    }
                }
            }
            form.render('checkbox');
        }
    }, 'data');
}

function deleteData(data){
    let id = data.exportId;
    for(let j = 0; j < changeList.length; j++){
        if (changeList[j].exportId == id) {
            changeList.splice(j, 1); // 将使后面的元素依次前移，数组长度减1
            j--; // 如果不减，将漏掉一个元素
        }
    }
}

//子表单全选,则对应选中或取消
function checkedParent(tableCache, flag){
    //主表数据
    let parentData = layui.table.cache["purchaseordertableid"];
    if(tableCache.length > 0 && parentData.length > 0){
        //对应主表id
        let id = tableCache[0].id;
        for (let i in parentData) {
            if(parentData[i].exportId == id){
                if(flag){
                    parentData.data[i].LAY_CHECKED = 'true';
                    return false;
                }else{
                    parentData.data[i].LAY_CHECKED = 'false';
                    return false;
                }
            }
            return false;
        }
    }
    //重新加载主表
    table.reload('purchaseordertableid', {data:parentData});
}

//复选框子表
table.on('checkbox(producttable)', function (obj) {
    if ( obj.type == 'one' ) {
        if (obj.checked) {
            //第一个表格选中的数据
            let tableData = table.cache["purchaseordertableid"];
            //外销合同号
            let exportNo = "";
            //账期
            let period = 0;
            //是否补货(0:否 1:是)
            let whetherToReplenish = 0;
            for(let i in tableData){
                if(obj.data["purchaseId"] === tableData[i]["exportId"]){
                    exportNo = tableData[i]["exportNo"];
                    period = tableData[i]["customerAccountingPeriod"];
                    whetherToReplenish = tableData[i]["whetherToReplenish"];
                    obj.data.companyId=tableData[i].companyId;
                    obj.data.salesmanCode=tableData[i].salesmanCode;
                    obj.data.signingCode=tableData[i].signingCode;
                    obj.data.signingName=tableData[i].signingName;
                    obj.data.bankCode=tableData[i].bankCode;
                    obj.data.bankName=tableData[i].bankName;
                    obj.data.customerLevelCode=tableData[i].customerLevelCode;
                    obj.data.customerLevelName=tableData[i].customerLevelName;
                    obj.data.importRemark=tableData[i].importRemark;
                    obj.data.whetherToReplenish=tableData[i].whetherToReplenish;
                    obj.data.customerComplaintNo=tableData[i].customerComplaintNo;
                    break;
                }
            }
            let sum = getReceivePaymentByContractNo(exportNo);
            if (isEmpty(period) && whetherToReplenish === 0 && sum === 0) {
                layer.msg("该合同未收预收款，请稍后再做采购，如有疑问请联系该单据业务员", {icon: 5});
                obj.checked = false;
            }else {
                changeList.push(obj.data);
            }
        } else {
            for (let index in changeList) {
                if (changeList[index].productId == obj.data.productId) {
                    changeList.splice(index,1);
                }
            }
        }
    } else if (obj.type == 'all') {
        let tableCache = table.checkStatus("producttableid").data;
    }
    form.render('checkbox');
});

//单击行事件
table.on('row(purchaseordertable)', function (obj) {
    let exportIds = [];
    exportIds.push(obj.data.exportId);
    table.reload('producttableid', {
        page: {
            limit: 10,
            curr: 1 //重新从第 1 页开始
        }
        ,where: {
            exIds:exportIds
        },
        parseData: function (res) {
            if (changeList) {
                for (let i in res.data) {
                    for (let j in changeList) {
                        if (changeList[j].exportNo == res.data[i].salesContractNo) {
                            res.data[i].LAY_CHECKED = 'true';
                        }
                    }
                }
            }
            return res;
        },
        done: function (res, curr, count) {

        }
    }, 'data');

});

//提交查询条件
form.on('submit(submitform)', function(data){
    let resultData = {};
    resultData.exportNo = $("input[name='exportNo']").val();
    resultData.customerContractNo = $("input[name='customerContractNo']").val();
    resultData.customerName = $("input[name='customerName']").val();
    resultData.productNo = $("input[name='productNo']").val();
    resultData.startDeliverTime = $("input[name='startDeliverTime']").val();
    resultData.endDeliverTime = $("input[name='endDeliverTime']").val();
    table.reload('purchaseordertableid', {
        page: {
            limit:10,
            curr: 1 //重新从第 1 页开始
        }
        ,url: 'purchase/selectExportByPage'
        ,where: resultData
    }, 'data');
    return false;
});

//根据供应商设置单价
function setCostPriceBySupplierCode(supplierCode, taxIncluded){
    let flag = true;
    if(isEmpty(supplierCode) || isEmpty(taxIncluded)){
        flag = false;
    }
    //获取备选供应商
    let alternative = [];
    $.ajax({
        url:"offer/getAlternativeSupplierList?supplierCode=" + supplierCode,
        async:false,
        success:function(data){
            if(data.status == 200){
                alternative = data.data;
            }
        }
    });
    if(isEmpty(alternative) || alternative.length === 0){
        //不在备选供应商,产品单价默认为0
        flag = false;
    }
    for(let i in changeList){
        //产品编码
        let productCode = changeList[i]["productNo"];
        //规格编码
        let specNo = changeList[i]["specNo"];
        if(isEmpty(alternative) || alternative.length === 0){
            //不在备选供应商,产品单价默认为0
            flag = false;
        }
        if(!flag){
            changeList[i]["costPrice"] = 0;
            continue;
        }
        let isFindFlag = false;
        for(let j in alternative){
            let flag = alternative[j]["productCode"] === productCode && alternative[j]["specNo"] === specNo
            if(flag){
                isFindFlag = true;
                switch (taxIncluded) {
                    case "1":
                        //含税出厂价
                        changeList[i]["costPrice"] = alternative[j]["taxIncludedPrice"];
                        break;
                    case "2":
                        //未税出厂价
                        changeList[i]["costPrice"] = alternative[j]["untaxedPrice"];
                        break;
                    case "3":
                        //含税FOB价
                        changeList[i]["costPrice"] = alternative[j]["taxIncludedFob"];
                        break;
                    case "4":
                        //未税FOB价
                        changeList[i]["costPrice"] = alternative[j]["untaxedFob"];
                        break;
                }
            }

        }
        if (!isFindFlag) {
            //不在备选供应商,产品单价默认为0
            changeList[i]["costPrice"] = 0;
        }
    }
}

$("#choose").on("click",function () {
    if(changeList.length == 0){
        layer.msg("请选择数据")
    }else{
        let oldData = parent.layui.table.cache["storageproductstableid"];
        //获取父页面选中的供应商编码
        let supplierCode = parent.$("#supplierCode").val();
        //获取父页面选中的是否含税
        let taxIncluded = parent.$("#taxIncluded").val();
        //根据供应商设置单价
        setCostPriceBySupplierCode(supplierCode, taxIncluded);
        let newData = [];
        let num = oldData.length+1;
        for(let i in changeList){
            changeList[i].tempId = num;
            changeList[i].amountNew = changeList[i].amount;
            changeList[i].requestDeliveryDate = layui.util.toDateString(changeList[i].requestDeliveryDate,"yyyy-MM-dd");
            //素材供应商 默认为"无"
            changeList[i]["materialSupplier"] = "无";
            newData.push(changeList[i]);
            num++;
        }
        oldData.push.apply(oldData, newData);
        parent.layui.table.reload('storageproductstableid', {data:oldData});
        setTimeout(function () {
            //保存成功则关闭此页面
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        },)
    }
})
$("#shutdown").on("click",function () {
    let index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
})

//字段是否为空或者零
function isEmpty(obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
        return true;
    }else{
        return false;
    }
}

//时间处理 获取当前时间type:1 yyyy-MM-dd type:2 yyyyMMdd+毫秒
function getNowFormatDate(type) {
    let date = new Date();
    let separator = "-";
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    if(1 == type){
        let currentDate = year + separator + month + separator + strDate;
        return currentDate;
    }else if(2 == type){
        let second = date.getMilliseconds().toString();
        if(second.length < 3){
            if(second.length == 1){
                second = "0" + "0" + second;
            }else {
                second = "0" + second;
            }
        }
        let currentDate = year.toString() + month.toString() + strDate.toString() + second;
        return currentDate;
    }

}
